package org.yar.activities;

import java.io.File;
import java.io.IOException;

import org.yar.R;
import org.yar.common.Preferences;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class WelcomeActivity extends ListActivity {
	static class ViewHolder {
		ImageView ivIcon;
		TextView tvFilename;
		TextView tvDesc;
		
		File file;
	}
	
	static class SavedFileAdapter extends ArrayAdapter<File> {
		
		private LayoutInflater inflater;
		private Preferences preferences;
		
		private Bitmap iconTextGeneric;
		
		public SavedFileAdapter(Context context, int textResourceId)
		{
			super(context, textResourceId);
			inflater = LayoutInflater.from(context);
			
			preferences = new Preferences(context);
			loadFromPreferences();
			
			iconTextGeneric = BitmapFactory.decodeResource(context.getResources(), R.drawable.text_x_generic);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			
			if (convertView == null)
			{
				convertView = inflater.inflate(R.layout.welcome_list_item, null);
				
				holder = new ViewHolder();
				holder.ivIcon = (ImageView)convertView.findViewById(R.id.ivIcon);
				holder.tvFilename = (TextView)convertView.findViewById(R.id.tvFilename);
				holder.tvDesc = (TextView)convertView.findViewById(R.id.tvDesc);
				
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder)convertView.getTag();
			}
			
			File f = getItem(position);
			
			holder.file = f;
			
			holder.tvFilename.setText(f.getName());
			holder.ivIcon.setImageBitmap(iconTextGeneric);
			
			
			try {
				holder.tvDesc.setText(formatDesc(f));
			} catch (Exception e) {
				Log.e(TAG, e.getMessage());
			}
			
			return convertView;
		}
		
		@Override
		public void remove(File f)
		{
			super.remove(f);
			preferences.removeFile(f);
			preferences.save();
		}
		
		public void save()
		{
			saveToPreferences();
			
			preferences.save();
		}
		
		private String formatDesc(File f) throws IOException
		{
			Long bytePos = preferences.getLong(f.getCanonicalPath(), "BYTE_POS", 0);
			Long length = preferences.getLong(f.getCanonicalPath(), "LENGTH", 0);
			
			if (length == 0)
			{
				return "-";
			}
			else
			{
				String prog = getContext().getResources().getString(R.string.welcome_progress);
				return String.format("%s %d%%", prog, bytePos*100/length);
			}
			
		}
		
		private void loadFromPreferences()
		{
			
			for (File file : preferences.getFiles())
			{
				add(file);
			}
		}
		
		private void saveToPreferences()
		{
			try {
				for (int i = 0; i < getCount(); ++i)
				{
					File f = getItem(i);
					preferences.addFile(f);
				}
			} catch (Exception e)
			{
				
			}
		}
	}
	
	private static String TAG = "YetAnotherReader.Welcome";
	
	private SavedFileAdapter adapter;
	private SharedPreferences sharedPrefs;
	private boolean loggedIn = false;
	
	private ViewFlipper vfWelcome;
	private Button btnOK;
	private EditText etPasswd;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);
        
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        
        vfWelcome = (ViewFlipper)findViewById(R.id.vfWelcome);
        btnOK = (Button)findViewById(R.id.btnOK);
        btnOK.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String password = sharedPrefs.getString(YARPreferencesActivity.PREF_PASSWD, "");
				String entered = etPasswd.getText().toString(); 
				Log.v(TAG, "entered: " + entered + " real: " + password);
				if (entered.equals(password))
				{
					Log.v(TAG, "logging in");
					vfWelcome.setDisplayedChild(1);
					loggedIn = true;
				}
				//TODO show 'Wrong password' dialog if password is not equal
			}
		});
        etPasswd = (EditText)findViewById(R.id.etPasswd);
        
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	
    	boolean usePassword = sharedPrefs.getBoolean(YARPreferencesActivity.PREF_USE_PASSWD, false);
    	if (!loggedIn && usePassword)
    	{
    		vfWelcome.setDisplayedChild(0);
    	}
    	else
    	{
    		vfWelcome.setDisplayedChild(1);
    		loggedIn = true;
    	}
    	
    	adapter = new SavedFileAdapter(this, R.layout.file_item);
    	
    	getListView().setAdapter(adapter);
    	
    	getListView().setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				SavedFileAdapter adapter = (SavedFileAdapter)getListView().getAdapter();
				File file = adapter.getItem(position);
				
				if (!file.canRead() || !file.exists())
				{
					return;
				}
				try {
					Intent intent = new Intent();
					intent.setClass(WelcomeActivity.this, ReaderActivity.class);
					intent.putExtra(ReaderActivity.READER_KEY_FILENAME, file.getCanonicalPath());

					startActivityForResult(intent, ReaderActivity.READER_CMD_OPEN_FILE);
				} catch (IOException ie)
				{
					Log.v(TAG, ie.getMessage());
				}
				
			}
    		
    	});
    	
    	registerForContextMenu(getListView());
    	
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info)
    {
    	super.onCreateContextMenu(menu, v, info);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.welcome_context_menu, menu);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item)
    {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
    	switch (item.getItemId())
    	{
    	case R.id.WCMDelete: {
    		removeRecentFile(adapter.getItem((int)info.id));
    		return true;
    	}
    	default:
    		return super.onContextItemSelected(item);
    	}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	if (!loggedIn)
    	{
    		return false;
    	}
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.welcome_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	switch (item.getItemId()) {
    	case R.id.WMFileBrowser: {
    		openFileBrowser();
    		return true;
    	}
    	case R.id.WMPreferences: {
    		openPreferences();
    		return true;
    	}
    	}
    		
    	
    	return super.onOptionsItemSelected(item);
    }
    
    private void removeRecentFile(File f)
    {
    	adapter.remove(f);
    }
    
    private void openFileBrowser()
    {
    	Intent intent = new Intent();
		intent.setClass(WelcomeActivity.this, FileBrowserActivity.class);
		
		startActivity(intent);
    }
    
    private void openPreferences()
    {
    	Intent intent = new Intent();
    	intent.setClass(WelcomeActivity.this, YARPreferencesActivity.class);
    	
    	startActivity(intent);
    }
}